package com.hqq.servlet;

import com.hqq.consts.ConfigConst;
import com.hqq.helper.BeanHelper;
import com.hqq.helper.ControllerHelper;
import com.hqq.http.*;
import com.hqq.loader.HelperLoader;
import com.hqq.util.*;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * DispatcherServlet
 * 控制转发器
 * Created by heqianqian on 2017/7/19.
 */
@WebServlet(urlPatterns = "/", loadOnStartup = 0)
public class DispatcherServlet extends HttpServlet {

    @Override
    public void init(ServletConfig config) throws ServletException {
        //初始化Helper类
        HelperLoader.init();
        System.out.println("init");
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.获取请求路径
        String requestPath = req.getServletPath();
        //2.获取请求参数
        //Map<String, Object> paramMap = new HashMap<>();
        Object[] params = new Object[req.getParameterMap().size()];
        int index = 0;
        Enumeration<String> parameterNames = req.getParameterNames();
        while (parameterNames.hasMoreElements()) {
            String parameter = req.getParameter(parameterNames.nextElement());
            params[index++] = parameter;
            //paramMap.put(parameterNames.nextElement(), req.getParameter(parameterNames.nextElement()));
        }
        //Param param = new Param(paramMap);
        //3.获取请求方法
        RequestMethod requestMethod = RequestMethod.getRequestMethod(req.getMethod());
        //4.获取handler处理器
        Handler handler = ControllerHelper.getHandler(requestMethod, requestPath);
        if (handler != null) {
            Class<?> controllerClass = handler.getControllerClass();
            Object controllerInstance = BeanHelper.getBean(controllerClass);
            Method method = handler.getRequestMethod();
            //5.调用相应的方法
            Object methodResult = null;
            //if (param.getPARAM_MAP().size() > 0) {//带参数
            if (params.length == 0) {
                methodResult = ReflectionUtil.invokeMethod(controllerInstance, method);
            } else {
                methodResult = ReflectionUtil.invokeMethod(controllerInstance, method, params);
            }
            //} else {//不带参数
            //    methodResult = ReflectionUtil.invokeMethod(controllerInstance, method);
            //}
            if (methodResult instanceof View) { //如果返回的是视图
                View view = (View) methodResult;
                req.getRequestDispatcher(ConfigUtil.getProjectJspPath() + view.getViewPath() + ConfigConst.PROJECT_JSP_SUFFIX).forward(req, resp);
            } else if (methodResult instanceof Data) { //如果返回的是json数据
                Data data = (Data) methodResult;
                Object modelData = data.getData();
                if (modelData != null) {
                    resp.setContentType("application/json");//设置返回的是json数据
                    resp.setCharacterEncoding("UTF-8");//设置编码
                    PrintWriter printWriter = new PrintWriter(resp.getOutputStream());
                    String json = JsonUtil.toJson(modelData);
                    printWriter.write(json);
                    printWriter.flush();
                    printWriter.close();
                }
            }
        }
    }
}
